//
//  HomViewController.m
//  MiniWeChat
//
//  Created by ByteDance on 2025/6/24.
//

#import "HomeViewController.h"
#import "ChatViewController.h"
#import "UserModel.h"
#import "ConversationTableViewCell.h"
#import "DBStorageService.h"


@interface HomeViewController ()

@end

@implementation HomeViewController

- (instancetype)initWithViewModel:(ConversationListViewModel *)viewModel {
    self = [super init];
    if (self) {
        _viewModel = viewModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupTableView];
    [self setupSearchBar];
    [self registerNotificationsListening];
    [self.viewModel fetchConversations];
}

// 视图即将显示时调用
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self.viewModel startNotificationListening];
}

// 视图即将消失时调用
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
//    [self.viewModel stopNotificationListening];
}

- (void)setupSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    self.searchBar.backgroundColor = [UIColor clearColor];
    self.searchBar.placeholder = @"搜索";
    self.searchBar.delegate = self;
    self.tableView.tableHeaderView = self.searchBar;
}

- (void)setupTableView {
    CGFloat tabBarHeight = self.tabBarController.tabBar.frame.size.height;
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - tabBarHeight) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerClass:[ConversationTableViewCell class] forCellReuseIdentifier:@"ConversationTableViewCell"];
    [self.view addSubview:_tableView];
}

- (void)registerNotificationsListening {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(conversationsUpdated:)
                                                 name:kNotificationConversationsUpdated
                                               object:nil];
    // 1. delegate
    // 2. kvo
    // 3. rac
    // 4. block
    
}

- (void)conversationsUpdated:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.viewModel numberOfConversations];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ConversationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConversationTableViewCell" forIndexPath:indexPath];
    ConversationModel *conversation = [self.viewModel conversationAtIndex:indexPath.row];
    [cell setConversation:conversation];
    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ConversationModel *conversation = [self.viewModel conversationAtIndex:indexPath.row];
    
    // 1. 若聊天会话未读 则标记为已读
    [self.viewModel markConversationAsReadAtIndex:indexPath.row];
    
    // 2. 跳转到聊天详情页
    ChatViewController *chatVC = [[ChatViewController alloc] initWithConversation:conversation];
    [self.navigationController pushViewController:chatVC animated:YES];
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ConversationModel  *conversation = [self.viewModel conversationAtIndex:indexPath.row];
    
    // 标为已读或未读
    UIContextualAction *markAsReadOrUnreadAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                                           title:conversation.unread_count > 0 ?  @"标为已读" : @"标为未读"
                                                                                         handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationMarkAsReadOrUnread object:self userInfo:@{@"conversation":conversation}];
        completionHandler(YES);
    }];
    markAsReadOrUnreadAction.backgroundColor = [UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1.0];
    
    UIContextualAction *notDisplayAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal
                                                                                   title:@"不显示"
                                                                                 handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        NSLog(@"不显示");
        completionHandler(YES);
    }];
    
    // 删除
    UIContextualAction *deleteAction =[UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive
                                                                              title:@"删除"
                                                                            handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {
        NSLog(@"删除");
        completionHandler(YES);
    }];
    
    // 创建配置
    UISwipeActionsConfiguration *configuration = [UISwipeActionsConfiguration configurationWithActions:@[deleteAction, notDisplayAction, markAsReadOrUnreadAction]];
    configuration.performsFirstActionWithFullSwipe = NO; // 关闭全屏滑动触发第一个动作
    
    return configuration;
}



- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:kNotificationConversationsUpdated
                                                  object:nil];
}

@end
